<template>
  <div>

    <km-space :spaces="spaces" @selected="selectSpace"></km-space>

    <q-input ref="menuFilter" dense filled v-model="menuFilter" label="搜索标题">
      <template v-slot:append>
        <q-icon v-if="menuFilter !== ''" name="clear" class="cursor-pointer" @click="resetFilter"/>
      </template>
    </q-input>

    <toggle v-if="$store.state.userInfo.role === 0" :options="[{option: '浏览模式', value: 6}, {option: '管理模式', value: -1}]"
            :visiting="visiting" @mode="handleMode"/>

    <q-list v-for="menu in menus" :key="menu._id">
      <!-- 使用这个组件，并绑定数据 -->
      <q-item-section>
        <Item :model="menu" :filtingShow="filtingShow" :drag="$store.state.userInfo.role === 0"
              @open="hadnleOpen"></Item>
      </q-item-section>
    </q-list>
  </div>
</template>
<script>
import iContent from 'src/api/content'
import Item from 'src/components/tree/Tree.vue'
import Toggle from 'src/components/Toggle.vue'
import KmSpace from 'src/pages/km/SpacesComponents.vue'
import { cloneDeep } from 'lodash'

export default {
  name: 'Menus',
  components: {
    Item,
    Toggle,
    KmSpace
  },
  data () {
    return {
      keywords: '',
      menuFilter: '',
      drawer: true,
      visiting: 6,
      filtingShow: false,
      spaces: [{
        _id: '',
        name: ''
      }]
    }
  },
  computed: {
    menus () {
      let menus = cloneDeep(this.$store.state.km.menu.list)
      if (this.menuFilter && this.menuFilter.length > 0) {
        const filterMenus = this.filterMenu(menus)
        menus = this.array2Tree(filterMenus, '', 0, '')
      }
      return menus
    }
  },
  watch: {
    menuFilter (newValue) {
      if (newValue.length > 0) {
        this.filtingShow = true
        // console.log('this.filtingShow = true')
      } else {
        this.filtingShow = false
      }
    }
  },
  async mounted () {
    this.spaces = await iContent.getKmSpaces()
    if (this.$route.query.sid) {
      // 优化用传过来的spaceid
      this.space = this.$route.query.sid
    } else {
      // 默认第1个
      this.space = this.spaces[0]._id
    }
    this.$store.dispatch('km/initMenu', {
      status: this.viewMode,
      kmSpaceId: this.space
    })
  },
  methods: {
    async selectSpace (spaceId) {
      this.$store.dispatch('km/initMenu', {
        status: this.viewMode,
        kmSpaceId: spaceId
      })
    },
    handleMode (mode) {
      this.visiting = mode
      this.$store.dispatch('km/initMenu', {
        status: this.visiting,
        kmSpaceId: this.$route.query.sid
      })
    },
    filterMenu (tree) {
      let menuSorts = []
      tree.forEach(e => {
        const t = cloneDeep(e)
        if (e.children && e.children.length > 0) {
          // 有children，判断children中是否有，有的话，本节点也要保留
          const childrenMenus = this.filterMenu(e.children)
          if (childrenMenus.length > 0) {
            menuSorts.push(t)
            menuSorts = menuSorts.concat(childrenMenus)
          }
        } else {
          // 没有children，直接判断是否有关键词
          if (e.title.toLowerCase().indexOf(this.menuFilter.toLowerCase()) >= 0) menuSorts.push(t)
        }
      })
      return menuSorts
    },
    tree2Array (tree) {
      let menuSorts = []
      tree.forEach(e => {
        const t = cloneDeep(e)
        if (e.children && e.children.length > 0) {
          menuSorts = menuSorts.concat(this.tree2Array(e.children))
        }
        menuSorts.push(t)
      })
      return menuSorts
    },
    array2Tree (data, pid, level, parentPrefix) {
      level++
      let showSeq = 1
      const res = []
      data.forEach(item => {
        if (item.parentId === pid) {
          item.level = level
          item.showSeq = showSeq++
          if (parentPrefix === '') {
            item.prefix = item.seq
          } else {
            item.prefix = parentPrefix + '.' + item.seq
          }
          // item.title = item.prefix + ' ' + item.title
          // item.title = item.showSeq + ' ' + item.title
          const itemChildren = this.array2Tree(data, item._id.toString(), level, item.prefix)
          item.children = itemChildren
          // q-menu不允许有相同的id，故生成新id，因为1个标签会有多个父标签
          // item.menuId = ++i
          res.push(item)
        }
      })
      return res
    },
    async hadnleOpen (id) {
      console.log(this.$route.path)
      console.log(this.$route.query.id)
      console.log(id)
      console.log(this.$route.path === '/km/article' && id === this.$route.query.id)
      if (!(this.$router.path === '/km/article' && id === this.$route.query.id)) {
        this.$router.push({
          path: '/km/article',
          query: { id: id }
        })
      }
    },
    resetFilter () {
      this.menuFilter = ''
      this.$refs.menuFilter.focus()
    }
  }
}
</script>

<style lang='scss'>

</style>
